﻿using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;

namespace ZBJF.Warranty.BLL
{
    public partial class InsuranceWarrantyRecordService
    {
        #region 根据报案单ID获取报案详情 InsuranceWarrantyRecord LoadByID(long id)
        public InsuranceWarrantyRecord LoadByID(long id)
        {
            return LoadEntities(o => o.ID == id).FirstOrDefault();
        }
        #endregion

        #region 根据工单ID 获取报案列表 IQueryable<InsuranceWarrantyRecord> LoadByInsuranceOrderId(long insuranceOrderId)
        public IQueryable<InsuranceWarrantyRecord> LoadByInsuranceOrderId(long insuranceOrderId)
        {
            return LoadEntities(o => o.InsuranceOrderId == insuranceOrderId);
        }
        #endregion

        #region 根据报案单号判断是否存在 bool IsExist(string warrantyRecordNo)
        public bool IsExist(string warrantyRecordNo)
        {
            return LoadEntities(o => o.WarrantyRecordNo.Equals(warrantyRecordNo)).Any();
        }
        #endregion

        #region 根据报案单号和付款金额获取报案信息 bool IsExistWarrantyRecordNo(string warrantyRecordNo, decimal paymentedAmount, ref InsuranceWarrantyRecord existEntity)
        public bool IsExistWarrantyRecordNo(string warrantyRecordNo, decimal paymentedAmount, ref InsuranceWarrantyRecord existEntity)
        {
            existEntity = LoadByWarrantyRecordNo(warrantyRecordNo, paymentedAmount);
            return existEntity != null;
        }
        #endregion

        #region 根据被保险人和应收金额获取报案信息  bool IsExistByUserNameReceivedPrice(string userName, decimal receivedAmount, ref InsuranceWarrantyRecord existEntity)
        public bool IsExistByUserNameReceivedPrice(string userName, decimal receivedAmount, ref InsuranceWarrantyRecord existEntity)
        {
            existEntity = LoadByUserName(userName, receivedAmount);
            return existEntity != null;
        }
        #endregion

        #region 根据被保险人和应收金额返回报案信息  InsuranceWarrantyRecord LoadByUserName(string userName, decimal receivedAmount)
        public InsuranceWarrantyRecord LoadByUserName(string userName, decimal receivedAmount)
        {
            return LoadEntities(o => o.InsuranceOrder.UserName.Equals(userName) && o.ReceivableAmount == receivedAmount)
                 .FirstOrDefault();
        }
        #endregion

        #region 根据报案单号和付款金额返回报案信息  InsuranceWarrantyRecord LoadByWarrantyRecordNo(string warrantyRecordNo, decimal paymentedAmount)
        public InsuranceWarrantyRecord LoadByWarrantyRecordNo(string warrantyRecordNo, decimal paymentedAmount)
        {
            return LoadEntities(o => o.WarrantyRecordNo.Equals(warrantyRecordNo) && o.PayableAmount == paymentedAmount)
                .FirstOrDefault();
        }
        #endregion

        public IQueryable<InsuranceWarrantyRecord> GetPagingList(InsuranceWarrantyRecordModel model, out int total)
        {
            var whereExpression = PredicateExtensions.True<InsuranceWarrantyRecord>();
            if (model.IsProcessing.HasValue)
            {
                //获取页面状态集合
                List<byte> statusList = GetStatusList(model.IsProcessing.Value ? InsuranceWarrantyRecordTaskType.ToBeProcess : InsuranceWarrantyRecordTaskType.Processed);

                whereExpression = whereExpression.And(o => statusList.Contains(o.Status));
            }
            if (!string.IsNullOrWhiteSpace(model.WarrantyRecordNo))
            {
                whereExpression = whereExpression.And(o => o.WarrantyRecordNo.Contains(model.WarrantyRecordNo.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.Reporter))
            {
                whereExpression = whereExpression.And(o => o.Reporter.Equals(model.Reporter.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.ReporterPhone))
            {
                whereExpression = whereExpression.And(o => o.ReporterPhone.Equals(model.ReporterPhone.Trim()));
            }
            if (model.Status.HasValue)
            {
                whereExpression = whereExpression.And(o => o.Status.Equals(model.Status.Value));
            }
            if (!string.IsNullOrEmpty(model.ProductName))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.ProductName.Contains(model.ProductName.Trim()));
            }
            if (model.ReceiptStatus.HasValue)
            {
                if (model.ReceiptStatus.Value == (byte)InsuranceWarrantyReceiptStatus.WaitToReceipt)
                {
                    whereExpression =
                        whereExpression.And(o => o.ReceiptStatus == (byte)InsuranceWarrantyReceiptStatus.WaitToReceipt);
                }
                else if (model.ReceiptStatus.Value == (byte)InsuranceWarrantyReceiptStatus.Receipted)
                {
                    whereExpression =
                        whereExpression.And(o => o.ReceiptStatus == (byte)InsuranceWarrantyReceiptStatus.Receipted);
                }
                else
                {
                    whereExpression =
                       whereExpression.And(o => o.ReceiptStatus == (byte)InsuranceWarrantyReceiptStatus.PartReceipt);
                }
            }
            if (model.PaymentStatus.HasValue)
            {
                if (model.PaymentStatus.Value == (byte)InsuranceWarrantyPaymentStatus.Paymented)
                {
                    whereExpression =
                        whereExpression.And(o => o.PaymentStatus == (byte)InsuranceWarrantyPaymentStatus.Paymented);
                }
                else if (model.PaymentStatus.Value == (byte)InsuranceWarrantyPaymentStatus.WaitToPayment)
                {
                    whereExpression =
                        whereExpression.And(o => o.PaymentStatus == (byte)InsuranceWarrantyPaymentStatus.WaitToPayment);
                }
                else
                {
                    whereExpression =
                       whereExpression.And(o => o.PaymentStatus == (byte)InsuranceWarrantyPaymentStatus.PartPayment);
                }
            }
            if (!string.IsNullOrEmpty(model.SendExpressNo))
            {
                whereExpression = whereExpression.And(o => o.SendExpressNo == model.SendExpressNo.Trim());
            }
            //维修方式
            if (model.WarrantyMaintenanceTypeID.HasValue)
            {
                whereExpression = whereExpression.And(o => o.WarrantyMaintenanceTypeID == model.WarrantyMaintenanceTypeID);
            }
            //付款状态下，只获取关单数据
            if (model.FinanceType.HasValue && model.FinanceType.Value == 2)
            {
                whereExpression = whereExpression.And(o => o.Status == (byte)InsuranceWarrantyStatus.Close);
            }
            if (!string.IsNullOrWhiteSpace(model.OrderNO))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.OrderNO.Contains(model.OrderNO.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.UserPhone))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.UserPhone.Contains(model.UserPhone.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.UserName))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.UserName.Contains(model.UserName.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.CertificateNO))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.CertificateNO.Contains(model.CertificateNO.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.InsuranceCategoryName))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.InsuranceCategoryName.Contains(model.InsuranceCategoryName.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.IMEI))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.IMEI.Equals(model.IMEI.Trim()));
            }
            if (model.InsuranceCompanyID > 0)
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.InsuranceCompanyID == (model.InsuranceCompanyID));
            }
            if (!string.IsNullOrWhiteSpace(model.InsuranceCompany))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.InsuranceCompany.Contains(model.InsuranceCompany.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.InsuranceCompanyBranch))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.InsuranceCompanyBranch.Contains(model.InsuranceCompanyBranch.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.SaleVendorName))
            {
                whereExpression = whereExpression.And(o => o.InsuranceOrder.SaleVendorName.Contains(model.SaleVendorName.Trim()));
            }
            if (model.ServiceStartTime.HasValue)
            {
                whereExpression =
                    whereExpression.And(o => o.InsuranceOrder.ServiceStartTime >= model.ServiceStartTime);
            }
            if (model.ServiceStartTime1.HasValue)
            {
                whereExpression =
                   whereExpression.And(o => o.InsuranceOrder.ServiceStartTime < SqlFunctions.DateAdd("dd", 1, model.ServiceStartTime1));
            }
            if (model.ServiceEndTime.HasValue)
            {
                whereExpression =
                    whereExpression.And(o => o.InsuranceOrder.ServiceEndTime >= model.ServiceEndTime);
            }
            if (model.ServiceEndTime1.HasValue)
            {
                whereExpression =
                    whereExpression.And(o => o.InsuranceOrder.ServiceEndTime < SqlFunctions.DateAdd("dd", 1, model.ServiceEndTime1));
            }
            if (!string.IsNullOrEmpty(model.SortingCenterName))
            {
                whereExpression =
                        whereExpression.And(o => o.SortingCenter.SortingCenterName == model.SortingCenterName);
            }
            //属于哪个页面。 根据不同的页面筛选不同的状态
            if (model.InsuranceWarrantyRecordTaskType.HasValue)
            {
                //获取页面状态集合
                List<byte> statusList = GetStatusList(model.InsuranceWarrantyRecordTaskType.Value);
                whereExpression = whereExpression.And(o => statusList.Contains(o.Status));
            }
            if (model.SystemServiceUserId.HasValue)
            {
                whereExpression =
                        whereExpression.And(o => o.SystemServiceUserId == model.SystemServiceUserId);
            }
            if (model.CreateTimeStart.HasValue)
            {
                whereExpression =
                        whereExpression.And(o => o.CreateTime >= model.CreateTimeStart);
            }
            if (model.CreateTimeEnd.HasValue)
            {
                whereExpression =
                        whereExpression.And(o => o.CreateTime < SqlFunctions.DateAdd("dd", 1, model.CreateTimeEnd));
            }
            //关单时间-开始（最后修改时间）
            if (model.CloseOrderTimeStart.HasValue)
            {
                whereExpression =
                        whereExpression.And(o => o.LastModifyTime >= model.CloseOrderTimeStart);
            }
            //关单时间-结束（最后修改时间）
            if (model.CloseOrderTimeEnd.HasValue)
            {
                whereExpression =
                        whereExpression.And(o => o.LastModifyTime < SqlFunctions.DateAdd("dd", 1, model.CloseOrderTimeEnd));
            }
            if (!string.IsNullOrEmpty(model.ThirdOrderNO))
            {
                whereExpression =
                        whereExpression.And(o => o.InsuranceOrder.ThirdOrderNO == model.ThirdOrderNO.Trim());
            }
            if (string.IsNullOrEmpty(model.iSorts))
            {
                model.iSorts = "CreateTime desc";
            }
            return LoadPagerEntities<InsuranceWarrantyRecord>(model.PageIndex, model.iDisplayLength, out total,
                whereExpression, model.iSorts);
        }
        #region 根据页面传值获取对应的报案单列表 IQueryable<InsuranceWarrantyRecord> LoadByInsuranceWarrantyRecordTaskType(byte insuranceWarrantyRecordTaskType=0)
        public IQueryable<InsuranceWarrantyRecord> LoadByInsuranceWarrantyRecordTaskType(byte insuranceWarrantyRecordTaskType = 0)
        {
            var whereExpression = PredicateExtensions.True<InsuranceWarrantyRecord>();
            //属于哪个页面。 根据不同的页面筛选不同的状态
            if (insuranceWarrantyRecordTaskType > 0)
            {
                //获取页面状态集合
                List<byte> statusList = GetStatusList((InsuranceWarrantyRecordTaskType)insuranceWarrantyRecordTaskType);
                whereExpression = whereExpression.And(o => statusList.Contains(o.Status));
            }
            return LoadEntities(whereExpression);
        }
        #endregion
        #region 获取搜索的工单状态列表 + List<byte> GetStatusList(InsuranceWarrantyRecordTaskType insuranceWarrantyRecordTaskType)
        /// <summary>
        /// 获取搜索的工单状态列表
        /// </summary>
        /// <returns></returns>
        public List<byte> GetStatusList(InsuranceWarrantyRecordTaskType insuranceWarrantyRecordTaskType)
        {
            switch (insuranceWarrantyRecordTaskType)
            {
                case InsuranceWarrantyRecordTaskType.ToBeProcess:
                case InsuranceWarrantyRecordTaskType.ToBeMaintainWorkOrder:
                    return ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadEntities(t => t.ParentCode == (byte)InsuranceWarrantyStatus.Processing).Select(t => t.StatusCode).ToList();
                case InsuranceWarrantyRecordTaskType.InSortingWorkOrder:
                    return ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadEntities(t => t.ParentCode == (byte)InsuranceWarrantyStatus.InSorting).Select(t => t.StatusCode).ToList();
                case InsuranceWarrantyRecordTaskType.MaintenanceWorkOrder:
                    return ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadEntities(t => t.ParentCode == (byte)InsuranceWarrantyStatus.InMaintain).Select(t => t.StatusCode).ToList();
                case InsuranceWarrantyRecordTaskType.Processed:
                case InsuranceWarrantyRecordTaskType.ProcessedWorkOrder:
                    return ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadEntities(t => t.ParentCode == (byte)InsuranceWarrantyStatus.Processed).Select(t => t.StatusCode).ToList();
                case InsuranceWarrantyRecordTaskType.ToBeReturnVisit:
                    return new List<byte>() { (byte)InsuranceWarrantyStatus.Close };
                case InsuranceWarrantyRecordTaskType.ReturnVisited:
                    return new List<byte>() { (byte)InsuranceWarrantyStatus.RetrurnVisited };
                case InsuranceWarrantyRecordTaskType.HadCancel:
                    return new List<byte>() { (byte)InsuranceWarrantyStatus.Canceled };
                default:
                    return new List<byte>();
            }
        }
        #endregion

    }
}
